<?php

namespace app\admin\controller;

use app\models\{Shoplist, Cate, Goods, GoodsSpec, Order, OrderGoods, User, Region, Withdrawal, ShopLog, Rank, Admin, AdminMoney};
use think\Db;
use think\Validate;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;

class Shop extends Base
{

    public function import_batch_send()
    {
        //ini_set('memory_limit', '102400M'); //升级为256M内存
        $imageFilePath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/xlsimgs/'; //图片本地存储的路径
        if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
            mkdir($imageFilePath, 777, true);
        }
        try {
            //上传excel文件
            $file = request()->file('file');
            $file_size = $_FILES['file']['size'];
            if ($file_size > 10 * 1024 * 1024) {
                $this->error('文件大小不能超过10M');
                exit();
            }
            //将文件保存到public/uploads目录下面
            $info = $file->validate(['ext' => 'xls,xlsx'])->move('./uploads');
            if ($info) {
                //获取上传到后台的文件名
                $fileName = $info->getSaveName();
                //获取文件路径
                $filePath = $_SERVER['DOCUMENT_ROOT'] . '/uploads' . DIRECTORY_SEPARATOR . $fileName;
            } else {
                return json(['status' => '1', 'mag' => '文件过大或格式不正确导致上传失败-_-!']);
            }
            $objRead = IOFactory::createReader('Xlsx');
            $objRead->setReadDataOnly(true);
            $objSpreadsheet = $objRead->load($filePath);
            $objWorksheet = $objSpreadsheet->getSheet(0);
            $data = $objWorksheet->toArray();
            // foreach ($objWorksheet->getDrawingCollection() as $drawing) {
            //     list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
            //     $imageFileName = $drawing->getCoordinates() . mt_rand(1000, 9999);
            //     switch ($drawing->getExtension()) {
            //         case 'jpg':
            //         case 'jpeg':
            //             $imageFileName .= '.jpg';
            //             $source = imagecreatefromjpeg($drawing->getPath());
            //             imagejpeg($source, $imageFilePath . $imageFileName);
            //             break;
            //         case 'gif':
            //             $imageFileName .= '.gif';
            //             $source = imagecreatefromgif($drawing->getPath());
            //             imagegif($source, $imageFilePath . $imageFileName);
            //             break;
            //         case 'png':
            //             $imageFileName .= '.png';
            //             $source = imagecreatefrompng($drawing->getPath());
            //             imagepng($source, $imageFilePath . $imageFileName);
            //             break;
            //     }
            //     $startColumn = $this->ABC2decimal($startColumn);
            //     $data[$startRow - 1][$startColumn][] = url('/uploads/xlsimgs/' . $imageFileName, '', '', true);
            // }
        } catch (\Exception $e) {
            throw $e;
        }
        $error = [];
        if (count($data) > 1) {
            unset($data[0]);
            foreach ($data as $k => $goods) {
                if (empty($goods[0]) || empty($goods[1]) || empty($goods[2]) || empty($goods[3])) {
                    continue;
                }
                $saves = [];
                $shopid = (int)$goods[16];
                if (empty($shopid)) {
                    $shopid = 1;
                }
                $cateid = (new Cate())->where(['shopid' => $shopid, 'ishow' => 1, 'name' => $goods[6]])->value('id');
                if (empty($cateid)) {
                    $error[] = ['key' => $k + 1, 'msg' => '未找到商家分类'];
                    continue;
                }
                $good = (new Goods())->where(['goodsSn' => $goods[1], 'shopid' => $shopid, 'isdel' => 1])->find();
                if ((!empty($good) && empty($data['id']))) {
                    $error[] = ['key' => $k + 1, 'msg' => '商品编号已使用'];
                    continue;
                }
                $goodsDesc = '';
                if (!empty($goods[15])) {
                    foreach ($goods[15] as $descimg) {
                        $goodsDesc = $goodsDesc . '<div><img style="width:100%" src="' . $descimg . '"/></div>';
                    }
                }
                $saves = [
                    'title' => $goods[0],
                    'goodsSn' => $goods[1],
                    'shopid' => $shopid,
                    'cate' => $cateid,
                    'descs' => $goods[7] ?? '',
                    'isSale' => $goods[8] == '是' ? 1 : 2,
                    'isBest' => $goods[9] == '是' ? 1 : 2,
                    'isHot' => $goods[10] == '是' ? 1 : 2,
                    'isNew' => $goods[11] == '是' ? 1 : 2,
                    'brand' => $goods[12] ?? '',
                    'Keywords' =>  $goods[13] ?? '',
                    'images' =>  json_encode($goods[14], true),
                    'goodsDesc' =>  $goodsDesc,
                ];
                Db::startTrans();
                try {
                    $goodsid = (new Goods())->insertGetId($saves);
                    $spec['shopid'] = $shopid;
                    $spec['goodid'] =  $goodsid;
                    $spec['name'] = $goods[2];
                    $spec['price'] = $goods[3];
                    $spec['oprice'] = $goods[4];
                    $spec['goodsstock'] = $goods[5];
                    $spec['warnStock'] = 5;
                    (new GoodsSpec())->insert($spec);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $error[] = ['key' => $k + 1, 'msg' => $e->getMessage()];
                    continue;
                }
            }
        } else {
            return json(['status' => '1', 'msg' => '数据不足，无法导入']);
        }
        return json(['status' => 0, 'data' => $error, 'msg' => '操作成功']);
    }

    public function ABC2decimal($abc)
    {
        $ten = 0;
        $len = strlen($abc);
        for ($i = 1; $i <= $len; $i++) {
            $char = substr($abc, 0 - $i, 1); //反向获取单个字符

            $int = ord($char);
            $ten += ($int - 65) * pow(26, $i - 1);
        }
        return $ten;
    }

    public function shop_withdrawal()
    {
        $model = new Withdrawal();
        $data = $this->request->get();
        $result = $model->order('id desc');
        if (!empty($data['status'])) {
            $result = $result->where('status', $data['status']);
        }
        $result = $result->where('atype', 2)->where('shopid', $this->request->admin['id']);
        if (!empty($data['title'])) {
            $result = $result->where('name|cards', 'like', '%' . $data['title'] . '%');
        }
        $result = $result->paginate(10, false, ['query' => $this->request->param()]);
        return view(null, [
            'list' => $result
        ]);
    }


    public function shop_withdrawaledit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'money' => 'require|gt:0|float',
                'name' => 'require',
                'cards' => 'require',
                'type' => 'require|in:1,2,3',
                'bank' => 'require',
                'password' => 'require'
            ], [
                'money.require' => '金额不能为空',
                'money.gt' => '用户金额必须大于0',
                'money.float' => '用户金额必须为数字',
                'name.require' => '用户姓名不能为空',
                'cards.require' => '用户卡号|账号不能为空',
                'type.require' => '提现类型不能为空',
                'type.in' => '提现类型不正确',
                'bank.require' => '所属银行|公司不能为空',
                'password.require' => '密码不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $model = new Admin();
            $shoplogmodel = new AdminMoney();
            $withmodel = new Withdrawal();
            $shop = $model->where('id', $this->request->admin['id'])->find();
            if ($shop['money'] < abs($data['money'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '可提现余额不足']);
            }
            if ($shop['password'] != md5(md5($data['password']) . md5($shop['entry']))) {
                return json(['code' => 1, 'data' => [], 'msg' => '密码不正确']);
            }
            Db::startTrans();
            try {
                //返回商户余额
                $withmodel->save([
                    'atype' => 2,
                    'shopid' => $this->request->admin['id'],
                    'money' => $data['money'],
                    'name' =>  $data['name'],
                    'cards' =>  $data['cards'],
                    'bank' =>  $data['bank'],
                    'type' =>  $data['type'],
                    'status' => 1,
                ]);
                $model->MoneyEdit($shop, -abs($data['money']), 2, '申请提现,商家ID:' . $this->request->admin['id']);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        } else {
            $model = new Admin();
            $id = $this->request->get('id/d', 0);
            $results = $model->where('id', $id)->find();
            return view(null, [
                'row' => $results
            ]);
        }
    }


    public function shoprank()
    {
        $type = $this->request->get('type/d', 1);
        $model = new Shoplist();
        if ($type == 1) {
            $results = $model->order('total desc')->where('total', '>', 0);
        } else {
            $results = $model->order('todaytotal desc')->where('date', '>=', date('Y-m-d'));
        }
        $admin = $this->request->admin;
        if ($admin['type'] == 2) {
            $results = $results->where(['area' => $admin['area']]);
        }
        if ($admin['type'] == 3 || $admin['type'] == 4) {
            $results = $results->where(['street' => $admin['street']]);
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            if ($result['date'] < date('Y-m-d')) {
                $result['todaytotal'] = 0;
            }
            $result['province_text'] = (new Region())->where(['level' => 1, 'code' => $result['province']])->value('name');
            $result['city_text'] = (new Region())->where(['level' => 2, 'code' => $result['city']])->value('name');
            $result['area_text'] = (new Region())->where(['level' => 3, 'code' => $result['area']])->value('name');
            $result['street_text'] = (new Region())->where(['level' => 4, 'code' => $result['street']])->value('name');
        }
        return view(null, [
            'list' => $results
        ]);
    }

    public function shoplist()
    {
        $model = new Shoplist();
        $data = $this->request->get();
        $results = $model->order('id desc');
        if (!empty($data['title'])) {
            $results = $results->where('title|account', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['status'])) {
            $results = $results->where('status', $data['status']);
        }
        $admin = $this->request->admin;
        if ($admin['type'] == 2) {
            $results = $results->where(['area' => $admin['area']]);
        }
        if ($admin['type'] == 3 || $admin['type'] == 4) {
            $results = $results->where(['street' => $admin['street']]);
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            if ($result['date'] < date('Y-m-d')) {
                $result['todaytotal'] = 0;
            }
            $result['province_text'] = (new Region())->where(['level' => 1, 'code' => $result['province']])->value('name');
            $result['city_text'] = (new Region())->where(['level' => 2, 'code' => $result['city']])->value('name');
            $result['area_text'] = (new Region())->where(['level' => 3, 'code' => $result['area']])->value('name');
            $result['street_text'] = (new Region())->where(['level' => 4, 'code' => $result['street']])->value('name');
        }
        return view(null, [
            'list' => $results
        ]);
    }


    public function shoplist_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'remark' => 'require',
                'account' => 'require',
                'ranges' => 'require',
                'startsend' => 'require',
                'lat' => 'require',
                'lon' => 'require',
                'status' => 'require'
            ], [
                'title.require' => '商家名称不能为空',
                'remark.require' => '商家备注不能为空',
                'account.require' => '商家备注不能为空',
                'ranges.require' => '商家配送范围不能为空',
                'startsend.require' => '商家配送起送价不能为空',
                'lat.require' => '商家地址不能为空',
                'lon.require' => '商家地址不能为空',
                'status.require' => '商家状态不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            $url = 'https://apis.map.qq.com/ws/geocoder/v1';
            $resdata = [
                'location' => $data['lat'] . ',' . $data['lon'],
                'key' => '2AEBZ-YK23W-XISR6-ROOGV-VOLI7-46FFT'
            ];
            try {
                $result = api_curl($url, $resdata);
                $result = json_decode($result, true);
            } catch (\Exception $e) {
                $this->result([], 1, $e->getMessage());
            }
            $data['street'] = 0;
            if (!empty($result) && $result['status'] == 0) {
                if (!empty($result['result']['address_reference']['town']['id'])) {
                    $street = (new Region())
                        ->where(['level' => 4, 'code' => $result['result']['address_reference']['town']['id']])
                        ->find();
                } else {
                    $street = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $result['result']['ad_info']['adcode'])
                        ->where('name|remark', 'like', '%' . $result['result']['address_reference']['town']['title'] . '%')->find();
                }
                $data['street'] = $street['code'] ?? 0;
            }
            if (empty($data['street'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '街道不存在，']);
            }
            $area = (new Region())->where(['level' => 3, 'id' => $street['parent_id']])->find();
            if (empty($area)) {
                return json(['code' => 1, 'data' => [], 'msg' => '区域不存在']);
            }
            $city = (new Region())->where(['level' => 2, 'id' => $area['parent_id']])->find();
            if (empty($city)) {
                return json(['code' => 1, 'data' => [], 'msg' => '城市不存在']);
            }
            $province = (new Region())->where(['level' => 1, 'id' => $city['parent_id']])->find();
            if (empty($province)) {
                return json(['code' => 1, 'data' => [], 'msg' => '省份不存在']);
            }
            $data['area'] = $area['area_code'] ?? 0;
            $data['city'] = $city['area_code'] ?? 0;
            $data['province'] = $province['area_code'] ?? 0;
            $admin = $this->request->admin;
            if ($admin['type'] == 2 && !in_array($data['area'], $admin['area'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '无区域操作权限']);
            }
            if (($admin['type'] == 3 || $admin['type'] == 4) && !in_array($data['street'], $admin['street'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '无街道操作权限']);
            }
            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            $model = new Shoplist();
            //查找店铺名称、账号是否已经被使用
            $shopname = $model->where('title', $data['title'])->find();
            if (!empty($shopname)) {
                if (!empty($data['id']) && $data['id'] != $shopname['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '商家名称已被使用，请更改']);
                }
            }
            $shopaccount = $model->where('account', $data['account'])->find();
            if (!empty($shopaccount)) {
                if (!empty($data['id']) && $data['id'] != $shopaccount['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '商家账号已被使用，请更改']);
                }
            }
            if (!empty($data['id'])) {
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Shoplist();
            $id = $this->request->get('id/d', 0);
            $results = $model->where('id', $id)->find();
            return view(null, [
                'row' => $results
            ]);
        }
    }

    public function shoplog()
    {
        $model = new ShopLog();
        $shopmodel = new Shoplist();
        $data = $this->request->get();
        $results = $model->order('id desc');
        if (!empty($data['shopid'])) {
            $results = $results->where('shopid', $data['shopid']);
        }
        $result = $results->paginate(10, false, ['query' => $this->request->param()]);
        $shoplist = $shopmodel->field('id,title,account');
        $shoplist = $shoplist->select();
        foreach ($result as $results) {
            $results['shopname'] = $shopmodel->where('id', $results['shopid'])->value('title');
        }
        return view(null, [
            'shoplist' => $shoplist,
            'list' => $result
        ]);
    }

    public function shoplog_edit()
    {
        $money = $this->request->post('money/f', 0);
        $id = $this->request->post('id/d', 0);
        if (empty($id) || empty($money)) {
            return json(['code' => 1, 'data' => [], 'msg' => '参数错误，请重试']);
        }
        $model = new Shoplist();
        $shop = $model->where(['id' => $id])->find();
        if (empty($shop)) {
            return json(['code' => 1, 'data' => [], 'msg' => '商户不存在']);
        }
        Db::startTrans();
        try {
            (new ShopLog())->MoneyEdit($shop, $money, 4, '管理员操作,管理员ID:' . $this->request->admin['id']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
        }
        return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
    }

    public function goodslist()
    {
        $model = new Goods();
        $shopmodel = new Shoplist();
        $data = $this->request->get();
        $results = $model->where('isdel', 1)->order('id desc');
        if (!empty($data['title'])) {
            $results = $results->where('title', 'like', '%' . $data['title'] . '%');
        }
        if (!empty($data['goodsn'])) {
            $results = $results->where('goodsSn', $data['goodsn']);
        }
        if (!empty($data['cate'])) {
            $results = $results->where('cate', $data['cate']);
        }
        $cate = [];
        if (!empty($data['shopid'])) {
            $cate = (new Cate())->where(['shopid' => $data['shopid']])->select();
            $results = $results->where('shopid', $data['shopid']);
        }
        $admin = $this->request->admin;
        if ($admin['type'] == 2) {
            $shopid = $shopmodel->where(['area' => $admin['area']])->column('id');
            if (count($shopid) > 0) {
                $results = $results->where(['shopid' => $shopid]);
            } else {
                $results = $results->where(['shopid' => 0]);
            }
        }
        if ($admin['type'] == 3 || $admin['type'] == 4) {
            $shopid = $shopmodel->where(['street' => $admin['street']])->column('id');
            if (count($shopid) > 0) {
                $results = $results->where(['shopid' => $shopid]);
            } else {
                $results = $results->where(['shopid' => 0]);
            }
        }
        $result = $results->paginate(10, false, ['query' => $this->request->param()]);
        $shoplist = $shopmodel->field('id,title,account')->select();
        foreach ($result as $results) {
            $results['images'] = json_decode($results['images'], true) ?? [];
            $results['shopname'] = $shopmodel->where('id', $results['shopid'])->value('title');
            $results['catename'] = (new Cate())->where('id', $results['cate'])->value('name');
        }
        return view(null, [
            'shoplist' => $shoplist,
            'list' => $result,
            'cate' => $cate
        ]);
    }

    public function goodslist_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'goodsSn' => 'require',
                'shopid' => 'require',
                'cate' => 'require',
                'descs' => 'require',
                'isSale' => 'require|in:1,2',
                'isBest' => 'require|in:1,2',
                'isHot' => 'require|in:1,2',
                'isNew' => 'require|in:1,2',
                'goodsDesc' => 'require'
            ], [
                'title.require' => '商品名称不能为空',
                'goodsSn.require' => '商品编号不能为空',
                'shopid.require' => '商户ID不能为空',
                'cate.require' => '商品分类不能为空',
                'descs.require' => '商品描述不能为空',
                'isSale.require' => '上架类型不能为空',
                'isSale.in' => '上架类型不正确',
                'isBest.require' => '推荐类型不能为空',
                'isBest.in' => '推荐类型不正确',
                'isHot.require' => '热卖类型不能为空',
                'isHot.in' => '热卖类型不正确',
                'isNew.require' => '新品类型不能为空',
                'isNew.in' => '新品类型不正确',
                'goodsDesc.require' => '商品描述不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (!empty($data['images'])) {
                $data['images'] = json_encode($data['images'], true);
            }
            if (!empty($data['parpam'])) {
                $data['parpam'] = json_encode($data['parpam'], true);
            }
            if (empty($data['spec']) || count($data['spec']) <= 0) {
                return json(['code' => 1, 'data' => [], 'msg' => '规格信息不能少于一个']);
            }
            if (isset($data['file'])) {
                unset($data['file']);
            }
            $shopmodel = new Shoplist();
            $goodmodel = new Goods();
            $catemodel = new Cate();
            $specmodel = new GoodsSpec();
            //查找商家是否存
            $shoplist = $shopmodel->where('id', $data['shopid'])->find();
            if (!$shoplist) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家不存在']);
            }
            $admin = $this->request->admin;
            if ($admin['type'] == 2 && !in_array($shoplist['area'], $admin['area'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '无区域操作权限']);
            }
            if (($admin['type'] == 3 || $admin['type'] == 4) && !in_array($shoplist['street'], $admin['street'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '无街道操作权限']);
            }
            //查找分类是否存在
            $cate = $catemodel->where(['shopid' =>  $data['shopid'], 'id' => $data['cate']])->find();
            if (!$cate) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家分类不存在']);
            }
            //商品编号唯一
            $good = $goodmodel->where(['goodsSn' => $data['goodsSn'], 'shopid' => $data['shopid'], 'isdel' => 1])->find();
            if ((!empty($good) && empty($data['id']))) {
                return json(['code' => 1, 'data' => [], 'msg' => '商品编号已被使用']);
            }
            if (!empty($good) && !empty($data['id']) && $data['id'] != $good['id']) {
                return json(['code' => 1, 'data' => [], 'msg' => '商品编号已被使用']);
            }
            $insert = $data;
            unset($insert['spec']);
            if (empty($data['id'])) {
                Db::startTrans();
                try {
                    $data['id'] = $goodmodel->insertGetid($insert);
                    foreach ($data['spec'] as $spec) {
                        if (!empty($spec['id'])) {
                            $specmodel->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                        } else {
                            unset($spec['id']);
                            $spec['shopid'] = $shoplist['id'];
                            $spec['goodid'] =  $data['id'];
                            $specmodel->insert($spec);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
            } else {
                Db::startTrans();
                try {
                    $goodmodel->where('id', $data['id'])->update($insert);
                    foreach ($data['spec'] as $spec) {
                        if (!empty($spec['id'])) {
                            $specmodel->where(['goodid' => $data['id'], 'id' => $spec['id']])->update($spec);
                        } else {
                            unset($spec['id']);
                            $spec['shopid'] = $shoplist['id'];
                            $spec['goodid'] =  $data['id'];
                            $specmodel->insert($spec);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
                }
            }
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        } else {
            $model = new Goods();
            $specmodel = new GoodsSpec();
            $shopmodel = new Shoplist();
            $catemodel = new Cate();
            $cate = [];
            $id = $this->request->get('id/d', 0);
            $results = $model->where('id', $id)->find();
            $shoplist = $shopmodel->field('id,title,account')->select();
            if ($results) {
                $results['images'] = json_decode($results['images'], true) ?? [];
                $results['parpam'] = json_decode($results['parpam'], true) ?? [];
                $cate = $catemodel->where('shopid', $results['shopid'])->select();
                $results['speclist'] = $specmodel->order('is_default desc')->where(['shopid' => $results['shopid'], 'isdel' => 1, 'goodid' => $results['id']])->select();
            }
            return view(null, [
                'row' => $results,
                'shoplist' => $shoplist,
                'cate' => $cate
            ]);
        }
    }

    public function goodslist_del()
    {
        $id = trim(input('id'), ',');
        $model = new Goods();
        $res = $model->where(['id' => $id])->update(['isdel' => 2]);
        if ($res) {
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
    }

    public function goodsspec_del()
    {
        $id = trim(input('id'), ',');
        $model = new GoodsSpec();
        $goodsspec = $model->where(['id' => $id, 'isdel' => 1])->find();
        if (empty($goodsspec)) {
            return json(['code' => 1, 'data' => [], 'msg' => '库存规格不存在']);
        }
        //查询规格商品是否超过1个
        $havespec = $model->where(['goodid' => $goodsspec['goodid'], 'isdel' => 1])->count();
        if ($havespec <= 1) {
            return json(['code' => 1, 'data' => [], 'msg' => '库存规格必须保留一个']);
        }
        $res = $model->where(['id' => $id])->update(['isdel' => 2]);
        if ($res) {
            return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
    }

    public function order()
    {
        $model = new Order();
        $shopmodel = new Shoplist();
        $usermodel = new User();
        $regionmodel = new Region();
        $data = $this->request->get();
        $result = $model->order('id desc');
        if (!empty($data['ispay'])) {
            $result = $result->where('ispay', $data['ispay']);
        }
        if (!empty($data['user_id'])) {
            $result = $result->where('user_id', $data['user_id']);
        }
        if (!empty($data['payment'])) {
            $result = $result->where('payment', $data['payment']);
        }
        if (!empty($data['rece'])) {
            $result = $result->where('rece', $data['rece']);
        }
        if (!empty($data['status'])) {
            $result = $result->where('status', $data['status']);
        }
        if (!empty($data['shopid'])) {
            $result = $result->where('shopid', $data['shopid']);
        }
        if (!empty($data['ordersn'])) {
            $result = $result->where('ordersn', 'like', '%' . $data['ordersn'] . '%');
        }
        if (!empty($data['createtime1'])) {
            $result = $result->whereTime('created', '>=', $data['createtime1']);
        }
        if (!empty($data['createtime2'])) {
            $result = $result->whereTime('created', '<', $data['createtime2']);
        }
        if (!empty($data['finishtime1'])) {
            $result = $result->whereTime('fintime', '>=', $data['finishtime1']);
        }
        if (!empty($data['finishtime2'])) {
            $result = $result->whereTime('fintime', '<', $data['finishtime2']);
        }
        if (!empty($data['atype'])) {
            switch ($data['atype']) {
                case '1':
                    $result = $result->where(['type' => 1, 'status' => [3, 4]]);
                    break;
                case '2':
                    $result = $result->where(['type' => 2, 'status' => [3, 4]])->where('aid', '<>', $this->request->admin['id']);
                    break;
                case '3':
                    $result = $result->where(['type' => 2, 'status' => [3, 4]])->where('aid', $this->request->admin['id']);
                    break;
                default:
                    # code...
                    break;
            }
        }
        $admin = $this->request->admin;
        if ($admin['type'] == 2) {
            $shopid = $shopmodel->where(['area' => $admin['area']])->column('id');
            if (count($shopid) > 0) {
                $result = $result->where(['shopid' => $shopid]);
            } else {
                $result = $result->where(['shopid' => 0]);
            }
        }
        if ($admin['type'] == 3 || $admin['type'] == 4) {
            $shopid = $shopmodel->where(['street' => $admin['street']])->column('id');
            if (count($shopid) > 0) {
                $result = $result->where(['shopid' => $shopid]);
            } else {
                $result = $result->where(['shopid' => 0]);
            }
        }
        $sumtotal = $result->sum('total');
        $result = $result->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['user'] = $usermodel->where('id', $results['user_id'])->field('id,nickName,gender,avatarUrl,mobile')->find();
            $results['shop'] = $shopmodel->where('id', $results['shopid'])->find();
            $results['province_name'] = $regionmodel->where(['area_code' => $results['province'], 'level' => 1])->value('name');
            $results['city_name'] = $regionmodel->where(['area_code' => $results['city'], 'level' => 2])->value('name');
            $results['area_name'] = $regionmodel->where(['area_code' => $results['area'], 'level' => 3])->value('name');
            if ($results['payment'] == 1) {
                $results['payment_text'] = '货到支付';
            } else {
                $results['payment_text'] = '微信支付';
            }
            if ($results['rece'] == 1) {
                $results['rece_text'] = '正常';
            } else {
                $results['rece_text'] = '待售后';
            }
            switch ($results['status']) {
                case '1':
                    $results['status_text'] = '待付款';
                    break;
                case '2':
                    $results['status_text'] = '待配送';
                    break;
                case '3':
                    $results['status_text'] = '待收货';
                    break;
                case '4':
                    $results['status_text'] = '已完成';
                    break;
                case '5':
                    $results['status_text'] = '已取消';
                    break;
                default:
                    break;
            }
            //查询是否可以直接发货
            if (empty($results['aid']) || $results['status'] == 2 || $results['status'] == 1) {
                $admins = Db::name('admin')->where('find_in_set(' . $results['shop']['street'] . ',street)')->where(['type' => [3, 4]])->find();
                if (empty($admins)) {
                    $admins = Db::name('admin')->where('find_in_set(' . $results['shop']['area'] . ',area)')->where(['type' => [2]])->find();
                }
                $results['aaid'] = $admins['id'] ?? 0;
                $results['anickname'] = $admins['nickname'] ?? '';
            } else {
                if ($results['type'] <= 1) {
                    $results['aaid'] = 0;
                    $results['anickname'] = '';
                } else {
                    $admins = Db::name('admin')->where('id', $results['aid'])->find();
                    $results['aaid'] = $admins['id'] ?? -1;
                    $results['anickname'] = $admins['nickname'] ?? '合伙人删除';
                }
            }
        }
        $shoplist = $shopmodel->field('id,title,account')->select();
        if ($admin['type'] == 2) {
            $shoplist = $shopmodel->where(['area' => $admin['area']])->field('id,title,account')->select();
        }
        if ($admin['type'] == 3 || $admin['type'] == 4) {
            $shoplist = $shopmodel->where(['street' => $admin['street']])->select();
        }
        return view(null, [
            'shoplist' => $shoplist,
            'list' => $result,
            'adminid' => $this->request->admin['id'],
            'sumtotal' => $sumtotal
        ]);
    }

    public function order_goods()
    {
        $model = new OrderGoods();
        $ordersn = $this->request->get('ordersn', 0);
        $result = $model->where('ordersn', $ordersn)->order('id desc');
        $result = $result->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['images'] = json_decode($results['images'], true) ?? [];
        }
        return view(null, [
            'list' => $result
        ]);
    }

    public function order_status()
    {
        $model = new Order();
        $shopmodel = new ShopList();
        $id = $this->request->get('id/d', 0);
        $status = $this->request->get('status/d', 0);
        $order = $model->where('id', $id)->find();
        if (empty($order)) {
            return json(['code' => 1, 'data' => [], 'msg' => '订单不存在']);
        }
        $shoplist = $shopmodel->where('id', $order['shopid'])->find();
        if (!$shoplist) {
            return json(['code' => 1, 'data' => [], 'msg' => '商家不存在']);
        }
        $admin = $this->request->admin;
        if ($admin['type'] == 2 && !in_array($shoplist['area'], $admin['area'])) {
            return json(['code' => 1, 'data' => [], 'msg' => '无区域操作权限']);
        }
        if (($admin['type'] == 3 || $admin['type'] == 4) && !in_array($shoplist['street'], $admin['street'])) {
            return json(['code' => 1, 'data' => [], 'msg' => '无街道操作权限']);
        }
        Db::startTrans();
        try {
            $model->order_status($order, $status, 2, $this->request->admin['id']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
        }
        return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
    }
}
